package com.th.campusmatchbackend.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.th.campusmatchbackend.common.ErrorCode;
import com.th.campusmatchbackend.config.ThirdPartyLoginConfig;
import com.th.campusmatchbackend.exception.BusinessException;
import com.th.campusmatchbackend.model.domain.User;
import com.th.campusmatchbackend.model.request.QQLoginRequest;
import com.th.campusmatchbackend.model.vo.LoginInfoVo;
import com.th.campusmatchbackend.model.vo.QQLoginVo;
import com.th.campusmatchbackend.service.ThirdPartyLoginService;
import com.th.campusmatchbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;



@Service
@Slf4j
public class ThirdPartyLoginServiceImpl implements ThirdPartyLoginService {

    @Resource
    private ThirdPartyLoginConfig thirdPartyLoginConfig;
    @Resource
    private UserService userService;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "th";

    @Override
    public User getLonginInfo(QQLoginRequest qqLoginRequest, HttpServletRequest request) throws IOException {
        String requestUrl = String.format("https://uniqueker.top/connect.php?act=callback&appid=%s&appkey=%s&type=qq&code=%s"
                ,thirdPartyLoginConfig.getAppId(),thirdPartyLoginConfig.getAppKey(),qqLoginRequest.getCode());
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;


        try {
            client = HttpClients.createDefault();
            HttpGet requestBody = new HttpGet(requestUrl);
            response = client.execute(requestBody);
            String responseBody = EntityUtils.toString(response.getEntity());
            LoginInfoVo infoVo = new Gson().fromJson(responseBody, LoginInfoVo.class);
            User user = new User();
            if(infoVo.getCode().equals(0)){
                user.setUserAccount(infoVo.getSocial_uid());
                user.setUsername(infoVo.getNickname());
                user.setAvatarUrl(infoVo.getFaceimg());
                user.setTags("");
                user.setUserIds("");
                user.setUserStatus(0);
                user.setIsDelete(0);
                //默认普通用户
                user.setUserRole(0);
                //默认密码123456789
                String password = "123456789";
                //对默认密码加密，统一数据库中密码的格式
                String  encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
                user.setUserPassword(encryptPassword);
                LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userLambdaQueryWrapper.eq(User::getUserAccount, user.getUserAccount());
                User one = userService.getOne(userLambdaQueryWrapper);
                if(one != null){
                    return one;
                }else{
                    if("男".equals(infoVo.getGender())){
                        user.setGender(1);
                    }else{
                        user.setGender(0);
                    }
                    userService.save(user);
                }
                return user;

            }else{
                throw new BusinessException(ErrorCode.NULL_LOGIN, "请重新登录");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            assert response != null;
            response.close();
            client.close();
        }

    }

    @Override
    public String Login() throws IOException {
        String requestUrl = String.format("https://uniqueker.top/connect.php?act=login&appid=%s&appkey=%s&type=qq&redirect_uri=%s",
                thirdPartyLoginConfig.getAppId(), thirdPartyLoginConfig.getAppKey(), thirdPartyLoginConfig.getRedirectUrl());
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpGet request = new HttpGet(requestUrl);
            response = client.execute(request);
            String responseBody = EntityUtils.toString(response.getEntity());
            QQLoginVo qq = new Gson().fromJson(responseBody, QQLoginVo.class);
            log.info("qq信息={}", JSON.toJSONString(qq));
            return qq.getUrl();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            assert response != null;
            response.close();
        }


    }
}
